package com.swim.wechat.web;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.pojo.LoginRespones;
import com.jeesite.common.pojo.LoginUser;
import com.jeesite.common.utils.HttpClientUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.swim.sys.service.SysUserRoleService;
import com.swim.wechat.bean.Response;
import com.swim.wechat.bean.WxApiPhoneResp;
import com.swim.wechat.bean.WxRequest;
import com.swim.wechat.bean.WxUserEntity;
import com.xkzhangsan.time.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxUserController
 * @Description 微信小程序登录
 * @Author Spencer Zhang
 * @Date 2025/2/12 11:12
 */
@Slf4j
@RestController
@RequestMapping(value = "${adminPath}/wx/user")
public class WxUserController extends BaseController {

    private static final String BASE = "https://open.weixin.qq.com/connect/oauth2/authorize";
    private static final String REDIRECT_URI = "https://www.szyypx.com/swim/wx/user/callback";
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WechatAccountConfig wechatAccountConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    private static final String WX_API = "https://api.weixin.qq.com";
    private static final String GET_PHONE = "/wxa/business/getuserphonenumber";
    private static final String LOGIN = "/sns/jscode2session";
    private static final String VERIFY_INFO = "/donut/code2verifyinfo";

    @GetMapping("/test")
    @ResponseBody
    public String a() {
        return "OK";
    }

    @PostMapping("/getUserInfoByWxApi")
    @ResponseBody
    public Response getPhoneByWxApi(@RequestBody WxRequest body) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("code", body.getCode());
            log.info("code={}", body.getCode());
            WxApiPhoneResp resp = HttpClientUtils.sendMsg("post",
                    WX_API + GET_PHONE + "?access_token=" + wxMpService.getAccessToken(),
                    params,
                    WxApiPhoneResp.class
            );
            log.info("resp={}", resp.getErrcode());
            switch (resp.getErrcode()) {
                case "-1":
                    return Response.builder().errMsg(resp.getErrcode()).build();
                case "40029":
                    return Response.builder().errMsg("code无效").build();
                case "45011":
                    return Response.builder().errMsg("API 调用太频繁，请稍候再试").build();
                case "40013":
                    return Response.builder().errMsg("请求appid身份与获取code的小程序appid不匹配").build();
            }
            return Response.builder().result(resp.getPhoneInfo().getPurePhoneNumber()).build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.builder().errMsg("请求出错").build();
        }
    }

    @PostMapping("/wxLogin")
    public void wxLogin(@Valid WxRequest body, HttpServletRequest request, HttpServletResponse response, Model model) {
        System.out.println("test");
    }

    @GetMapping("/wxLogin")
    @ResponseBody
    public LoginRespones doWxLogin(@Valid WxRequest body, HttpServletRequest request, HttpServletResponse response, Model model) {
        Object principal = UserUtils.getSubject().getPrincipal();
        Assert.notNull(principal, "用户获取失败");

        User query = new User();
        query.setLoginCode(principal.toString());
        User user = userService.getByLoginCode(query);
        Session session = UserUtils.getSession();
        return LoginRespones.builder()
                .user(new LoginUser(user))
                .result("true")
                .message("登录成功！")
                .sessionid((String) session.getId())
                .build();
    }

    private void t(String token, String openId) {
        HttpClientUtils.createClient();
        CloseableHttpClient httpclient = HttpClientUtils.getCurrentClient();
        CloseableHttpResponse response = null;
        try {
            HttpPost httppost = new HttpPost("https://api.weixin.qq.com/sns/userinfo");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("access_token", token);
            builder.addTextBody("openid", openId);
            builder.addTextBody("lang", "zh_CN");

            HttpEntity multipart = builder.build();
            httppost.setEntity(multipart);
            response = httpclient.execute(httppost);// 发送请求

            String userinfo = EntityUtils.toString(response.getEntity());
            WxUserEntity user = JSON.parseObject(userinfo, WxUserEntity.class);
            log.debug("用户：" + user);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeResponse(response);
        }
    }

    @GetMapping("/callback")
    public void callback(@RequestParam("code") String code, ServletRequest request, ServletResponse response) throws IOException {
        if (StringUtil.isNotEmpty(code)) {
            WxOAuth2AccessToken accessToken = null;
            try {
                accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
                //从token中获取openId
                String openId = accessToken.getOpenId();
                log.debug("openId:" + openId);
                Assert.notNull(openId, "未找到微信用户信息");
                //可拉取信息
                if ("snsapi_userinfo".equals(accessToken.getScope().toLowerCase())) {
                    t(accessToken.getAccessToken(), openId);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        }
        WebUtils.issueRedirect(request, response, "https://www.szyypx.com/swim", null, true);
    }

//    private WxApiUserResp getUserInfoByWxApi(String code) {
//        Map<String, String> params = new HashMap<>();
//        params.put("appid", wechatAccountConfig.getAppId());
//        params.put("appsecret", wechatAccountConfig.getAppSecret());
//        params.put("code", code);
//        params.put("grant_type", "authorization_code");
//        return sendMsg("get", WX_API + VERIFY_INFO, params, WxApiUserResp.class);
//    }

//    @GetMapping("/getUserInfoByWxApi")
//    @ResponseBody
//    public Response getUserInfo(@Valid @RequestParam("code") String code) {
//        try {
//            wxMpService.getAccessToken();
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//        WxApiUserResp resp = getUserInfoByWxApi(code);
//        String openId = resp.getUserInfo().getUserId();
//        logger.debug("openId:" + openId);
//        User u = new User();
//        u.setWxOpenid(openId);
//        List<User> users = userService.findList(u);
//        if (users.isEmpty()) {
//            u.setUserCode(openId);
//            u.setLoginCode(openId);
//            u.setPassword("12345");
//            userService.insert(u);
//        } else {
//            u = users.get(0);
//        }
//        Subject currentUser = SecurityUtils.getSubject();
//        currentUser.login(new UsernamePasswordToken(u.getLoginCode(), u.getPassword(), request.getRemoteHost()));
//        switch (resp.getErrcode()) {
//            case "-1":
//                return Response.builder().errMsg(resp.getErrcode()).build();
//            case "10001000":
//                return Response.builder().errMsg("code过期").build();
//            case "10001001":
//                return Response.builder().errMsg("code错误").build();
//            case "10001002":
//                return Response.builder().errMsg("appid错误").build();
//            case "10001003":
//                return Response.builder().errMsg("appsecret错误").build();
//            case "10001004":
//                return Response.builder().errMsg("grant_type错误").build();
//        }
//        return Response.builder().result(resp.getUserInfo().getPhoneInfo()).build();
//    }

}